﻿using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;

namespace BssDs.Client.UI.Controls.ExtendedControl.Tab
{
	public class TabDraggingCursorAdorner : Adorner
	{
		private Rectangle _rect;
		private double _leftBase;
		private double _topBase;
		private double _left;
		private double _top;

		public TabDraggingCursorAdorner(TabControlEx tabControl)
			: base(tabControl)
		{
			Visibility = Visibility.Hidden;

			_rect = new Rectangle();
		}

		public void Show(TabItem item, Point position)
		{
			TabControlEx ownerTab = AdornedElement as TabControlEx;
			Debug.Assert(ownerTab != null);

			VisualBrush brush = new VisualBrush(item);
			if (ownerTab.DraggingCursorAdornerOpacityMask != null)
				_rect.OpacityMask = ownerTab.DraggingCursorAdornerOpacityMask;
			_rect.Fill = brush;
			_rect.Width = item.ActualWidth;
			_rect.Height = item.ActualHeight;

			Visibility = Visibility.Visible;

			Point offset = ownerTab.DraggingCursorAdornerOffset;
			_leftBase = (double.IsNaN(offset.X) ? 0 : offset.X);
			_topBase = (double.IsNaN(offset.Y) ? item.ActualHeight / 2.0 : offset.Y);
			_left = position.X;
			_top = position.Y;

			Update();
		}

		public void Move(Point position)
		{
			_left = position.X;
			_top = position.Y;

			Update();
		}

		public void Hide()
		{
			Visibility = Visibility.Hidden;
			_rect.Fill = null;
			_rect.Width = 0;
			_rect.Height = 0;
		}

		public void Update()
		{
			AdornerLayer layer = this.Parent as AdornerLayer;
			if (layer != null)
				layer.Update(this.AdornedElement);
		}

		public override GeneralTransform GetDesiredTransform(GeneralTransform transform)
		{
			GeneralTransformGroup result = new GeneralTransformGroup();
			result.Children.Add(base.GetDesiredTransform(transform));
			result.Children.Add(new TranslateTransform(
					_leftBase + _left,
					_topBase + _top
			));
			return result;
		}

		protected override Size ArrangeOverride(Size finalSize)
		{
			_rect.Arrange(new Rect(_rect.DesiredSize));
			return finalSize;
		}

		protected override int VisualChildrenCount
		{
			get
			{
				return 1;
			}
		}

		protected override Visual GetVisualChild(int index)
		{
			return _rect;
		}
	}
}
